package com.xnew.utils;

import java.security.MessageDigest;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

/**
 * AES加密工具类
 * 
 * @author huangqj
 * 
 */
public class AESHelper {

//	private static final Logger Log = Logger.getLogger(AESHelper.class);

	private static final String ENCODE = "UTF-8"; // AES加密时使用UTF8编码方式

	/**
	 * 
	 * @param encryptedString
	 *            密文
	 * @param key
	 *            密码
	 * @return
	 * @throws Exception
	 */
	public static String AESDecrypt(String encryptedString, String key)
			throws Exception {
		try {
			byte[] keyArray = shortMD5(key);
			SecretKeySpec skeySpec = new SecretKeySpec(keyArray, "AES");
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(Cipher.DECRYPT_MODE, skeySpec);
			byte[] encryptedData = Base64.decodeBase64(encryptedString
					.getBytes(ENCODE));
			byte[] original = cipher.doFinal(encryptedData);
			String originalString = new String(original, ENCODE);
			return originalString;
		} catch (Exception e) {
//			Log.error("AESDecrypt 解密异常：", e);			
			throw new Exception();
		}

	}

	/**
	 * 
	 * @param data
	 *            需加密明文数据
	 * @param key
	 *            加密密码
	 * @return
	 * @throws Exception
	 */	
	public static String AESEncrypt(String data, String key) throws Exception {
		try {
			byte[] plainBytes = data.getBytes(ENCODE);
			byte[] keyBytes = shortMD5(key);
			SecretKeySpec skeySpec = new SecretKeySpec(keyBytes, "AES");
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
			byte[] encrypted = cipher.doFinal(plainBytes);
			String encryptedString = new String(Base64.encodeBase64(encrypted),
					ENCODE);
			return encryptedString;
		} catch (Exception e) {
//			Log.error("AESEncrypt 加密异常：", e);			
			throw new Exception();
		}
	}

	private static byte[] shortMD5(String b) throws Exception {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(b.getBytes(ENCODE));
			byte[] digest = md.digest();
			return digest;
		} catch (Exception e) {
//			Log.error("shortMD5 获取MD5短信息异常：", e);				
			throw new Exception();
		}

	}

	public static void main(String[] args) throws Exception {
		String content = "现在开始与货运联调AES加解密，查看java与C#有通讯是否有问题？";

		// String pwd = AESCrypt.getRandomString();
		String pwd = "e55f915c93824f49804f495821a7c7ec";
		//String pwd = EncryptHelper.getRandomString();
		System.out.println("---------- 加密前内容: " + content);
		System.out.println("---------- 加密前密码: " + pwd);
		String afterEDS = AESHelper.AESEncrypt(content, pwd);
		System.out.println("---------- 加密后内容： " + afterEDS);
		String afterDecrypt = AESHelper.AESDecrypt(afterEDS, pwd);
		System.out.println("---------- 解密后内容：  " + afterDecrypt);

		
	}

}
